package com.frcdi.qms.masterdata.service.impl;


import com.frcdi.qms.common.constant.UserConstants;
import com.frcdi.qms.common.core.domain.TreeSelect;
import com.frcdi.qms.common.core.domain.entity.ProjectType;
import com.frcdi.qms.common.utils.StringUtils;
import com.frcdi.qms.masterdata.mapper.ProjectTypeMapper;
import com.frcdi.qms.masterdata.service.IProjectTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 检验项目类型Service业务层处理
 *
 * @author cell
 * @date 2023-09-12
 */
@Service
public class ProjectTypeServiceImpl implements IProjectTypeService
{
    private static final Logger log = LoggerFactory.getLogger(ProjectTypeServiceImpl.class);
    @Autowired
    private ProjectTypeMapper projectTypeMapper;

    /**
     * 查询检验项目类型
     *
     * @param id 检验项目类型主键
     * @return 检验项目类型
     */
    @Override
    public ProjectType selectProjectTypeById(Long id)
    {
        return projectTypeMapper.selectProjectTypeById(id);
    }

    /**
     * 查询检验项目类型列表
     *
     * @param projectType 检验项目类型
     * @return 检验项目类型
     */
    @Override
    public List<ProjectType> selectProjectTypeList(ProjectType projectType)
    {
        return projectTypeMapper.selectProjectTypeList(projectType);
    }

    /**
     * 新增检验项目类型
     *
     * @param projectType 检验项目类型
     * @return 结果
     */
    @Override
    public int insertProjectType(ProjectType projectType)
    {
        ProjectType info = projectTypeMapper.selectProjectTypeById(projectType.getParentId());
        // 填充修改父级列表数据
        projectType.setAncestors(info.getAncestors() + "," + projectType.getParentId());
        int row = projectTypeMapper.insertProjectType(projectType);
        return row;
    }

    /**
     * 修改检验项目类型
     *
     * @param projectType 检验项目类型
     * @return 结果
     */
    @Override
    public int updateProjectType(ProjectType projectType)
    {
        ProjectType newParent = projectTypeMapper.selectProjectTypeById(projectType.getParentId());
        ProjectType oldresult = projectTypeMapper.selectProjectTypeById(projectType.getId());
        if (StringUtils.isNotNull(newParent) && StringUtils.isNotNull(oldresult))
        {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = oldresult.getAncestors();
            projectType.setAncestors(newAncestors);
            updateProjectTypeChildren(projectType.getId(), newAncestors, oldAncestors);
        }
        int row = projectTypeMapper.updateProjectType(projectType);
        return row;
    }

    /**
     * 批量删除检验项目类型
     *
     * @param ids 需要删除的检验项目类型主键
     * @return 结果
     */
    @Override
    public int deleteProjectTypeByIds(Long[] ids)
    {
        int row = projectTypeMapper.deleteProjectTypeByIds(ids);
        return row;
    }

    /**
     * 删除检验项目类型信息
     *
     * @param id 检验项目类型主键
     * @return 结果
     */
    @Override
    public int deleteProjectTypeById(Long id)
    {
        int row = projectTypeMapper.deleteProjectTypeById(id);
        return row;
    }

    /**
     * 查询检验项目类型结构信息
     *
     * @param projectType 检验项目类型信息
     * @return 检验项目类型信息集合
     */
    @Override
    public List<TreeSelect> selectProjectTypeTreeList(ProjectType projectType) {
        List<ProjectType> projectTypes = this.selectProjectTypeList(projectType);
        return buildProjectTypeSelect(projectTypes);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param projectTypes 检验项目类型列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildProjectTypeSelect(List<ProjectType> projectTypes)
    {
        List<ProjectType> ProjectTypeTrees = buildProjectTypeTree(projectTypes);
        return ProjectTypeTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param projectTypes 检验项目类型列表
     * @return 树结构列表
     */
    @Override
    public List<ProjectType> buildProjectTypeTree(List<ProjectType> projectTypes)
    {
        List<ProjectType> returnList = new ArrayList<ProjectType>();
        List<Long> tempList = projectTypes.stream().map(ProjectType::getId).collect(Collectors.toList());
        for (ProjectType projectType : projectTypes)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(projectType.getParentId()))
            {
                recursionFn(projectTypes, projectType);
                returnList.add(projectType);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = projectTypes;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ProjectType> list, ProjectType t)
    {
        // 得到子节点列表
        List<ProjectType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ProjectType tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ProjectType> getChildList(List<ProjectType> list, ProjectType t)
    {
        List<ProjectType> tlist = new ArrayList<ProjectType>();
        Iterator<ProjectType> it = list.iterator();
        while (it.hasNext())
        {
            ProjectType n = (ProjectType) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ProjectType> list, ProjectType t)
    {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 是否存在检验项目类型子节点
     *
     * @param id 检验项目类型ID
     * @return 结果
     */
    @Override
    public boolean hasChildById(Long id) {
        int result = projectTypeMapper.hasChildById(id);
        return result > 0;
    }

    /**
     * 校验检验项目类型名称是否唯一
     *
     * @param projectType 检验项目类型信息
     * @return 结果
     */
    @Override
    public boolean checkProjectTypeNameUnique(ProjectType projectType) {
        Long typeId = StringUtils.isNull(projectType.getId()) ? -1L : projectType.getId();
        ProjectType info = projectTypeMapper.checkProjectTypeNameUnique(projectType.getProjectTypeName(), projectType.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != typeId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkProjectTypeExistProject(Long id) {
        int result = projectTypeMapper.checkProjectTypeExistProject(id);
        return result > 0;
    }

    /**
     * 修改子元素关系
     *
     * @param id 被修改的物料类型ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateProjectTypeChildren(Long id, String newAncestors, String oldAncestors)
    {
        List<ProjectType> children = projectTypeMapper.selectChildrenId(id);
        for (ProjectType child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            projectTypeMapper.updateProjectTypeChildren(children);
        }
    }
}
